using System;
using System.Collections.Generic;
using System.Web;

namespace Lswweb.Domain.ShoppingCart
{
    internal class SessionShoppingCart : IShoppingCart
    {
        private readonly string sessionKey = "mycart";
        private IDictionary<int, IShoppingCartItem> items;

        public SessionShoppingCart()
        {
            items = HttpContext.Current.Session[sessionKey] as IDictionary<int, IShoppingCartItem>;
            if (items == null)
            {
                items = new Dictionary<int, IShoppingCartItem>();
                HttpContext.Current.Session[sessionKey] = items;
            }
        }

        public void Add(IShoppingCartItem item)
        {
            if (!this.items.ContainsKey(item.ProductId))
                this.items.Add(item.ProductId, item);
            else
                this.items[item.ProductId].Quantity += item.Quantity;
        }

        public void Remove(IShoppingCartItem item)
        {
            Remove(item.ProductId);
        }
        public void Remove(int productId)
        {
            this.items.Remove(productId);
        }

        public bool Contains(int productId)
        {
            return this.items.ContainsKey(productId);
        }
        public bool Contains(IShoppingCartItem item)
        {
            return this.items.Values.Contains(item);
        }

        public void Clear()
        {
            this.items.Clear();
        }

        public decimal TotalPrice
        {
            get
            {
                decimal total = 0;

                foreach (IShoppingCartItem item in this.items.Values)
                    total += item.SubTotalPrice;

                return total;
            }
        }

        public ICollection<IShoppingCartItem> Items
        {
            get { return this.items.Values; }
        }

        public IShoppingCartItem this[int productId]
        {
            get { return (IShoppingCartItem)this.items[productId]; }
        }


        public int TotalWeight
        {
            get 
            {
                int total = 0;

                foreach (IShoppingCartItem item in this.items.Values)
                    total += item.SubTotalWeight;

                return total;
            }
        }
    }
}
